package cn.shenlong.mybatis.typehandler;

import java.io.ByteArrayInputStream;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

/**
 * BLOB类型到字符串的类型转换器
 * 
 * @author czllfy
 */
public class BlobStringTypeHandler implements TypeHandler<String> {

	/**
	 * 设置参数
	 * 
	 * <pre>
	 * 将字符串转换为UTF8编码的Byte数组
	 * </pre>
	 */
	public void setParameter(PreparedStatement ps, int i, String parameter,
			JdbcType jdbcType) throws SQLException {
		byte[] byteArray = null;
		try {
			byteArray = parameter.getBytes("UTF-8");
		} catch (Exception e) {
			byteArray = new byte[] {};
		}
		ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
		ps.setBinaryStream(i, bis, byteArray.length);
	}

	/**
	 * 获取结果集
	 */
	public String getResult(ResultSet rs, String columnName)
			throws SQLException {
		String rtn = "";
		try {
			Blob blob = rs.getBlob(columnName);
			byte[] byteArray = blob.getBytes(1, (int) blob.length());
			rtn = new String(byteArray, "UTF-8");
		} catch (Exception e) {
			rtn = "";
		}
		return rtn;
	}

	/**
	 * 获取结果集
	 */
	public String getResult(ResultSet rs, int columnIndex) throws SQLException {
		String rtn = "";
		try {
			Blob blob = rs.getBlob(columnIndex);
			byte[] byteArray = blob.getBytes(1, (int) blob.length());
			rtn = new String(byteArray, "UTF-8");
		} catch (Exception e) {
			rtn = "";
		}
		return rtn;
	}

	/**
	 * 获取结果集
	 */
	public String getResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		String rtn = "";
		try {
			Blob blob = cs.getBlob(columnIndex);
			byte[] byteArray = blob.getBytes(1, (int) blob.length());
			rtn = new String(byteArray, "UTF-8");
		} catch (Exception e) {
			rtn = "";
		}
		return rtn;
	}

}
